package com.unittec.zk.provider.exam.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.unittec.zk.provider.exam.entity.ElQu;
import com.unittec.zk.provider.scope.ThreadLocalScope;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unittec.zk.provider.exam.mapper.ElUserBookMapper;
import com.unittec.zk.provider.exam.entity.ElUserBook;
@Service
public class ElUserBookService extends ServiceImpl<ElUserBookMapper, ElUserBook> {

    @Resource
    private ElQuService elQuService;

    public void addBook(String examId, String quId) {
        QueryWrapper<ElUserBook> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(ElUserBook::getUserId, ThreadLocalScope.getAuthData().getUser())
                .eq(ElUserBook::getExamId, examId)
                .eq(ElUserBook::getQuId, quId);

        //查找已有的错题信息
        ElUserBook book = this.getOne(wrapper, false);


        // 问题
        ElQu qu = elQuService.getById(quId);

        if (book == null) {
            book = new ElUserBook();
            book.setExamId(examId);
            book.setUserId(ThreadLocalScope.getAuthData().getUser());
            book.setTitle(qu.getContent());
            book.setQuId(quId);
            book.setWrongCount(1);
            Integer maxSort = this.findMaxSort(examId, ThreadLocalScope.getAuthData().getUser());
            book.setSort(maxSort+1);

            this.save(book);
        } else {
            book.setWrongCount(book.getWrongCount()+1);
            this.updateById(book);
        }
    }

    /**
     * 查找最大的排序
     * @param userId
     * @return
     */
    private Integer findMaxSort(String examId, String userId){

        QueryWrapper<ElUserBook> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(ElUserBook::getExamId, examId)
                .eq(ElUserBook::getUserId, userId);
        wrapper.last(" ORDER BY `sort` DESC");

        ElUserBook book = this.getOne(wrapper, false);
        if(book == null){
            return 0;
        }
        return book.getSort();
    }

}
